#!/usr/bin/env node

/**
 * 图片优化系统最终演示
 * 展示完整的图片优化流程和性能
 */

const AdvancedImageOptimizer = require('../lib/utils/advanced-image-optimizer');
const fs = require('fs');
const path = require('path');

async function demonstrateImageOptimization() {
    console.log('🖼️  Vision Analyzer - 图片优化系统最终演示\n');

    const optimizer = new AdvancedImageOptimizer();

    // 查找测试图片
    const testFiles = fs.readdirSync('.').filter(f =>
        f.endsWith('.jpg') || f.endsWith('.jpeg') || f.endsWith('.png')
    );

    if (testFiles.length === 0) {
        console.log('❌ 没有找到测试图片，请先准备一些图片文件');
        return;
    }

    console.log(`📁 找到 ${testFiles.length} 个测试图片:`);
    testFiles.forEach((file, index) => {
        const stats = fs.statSync(file);
        console.log(`   ${index + 1}. ${file} (${(stats.size / 1024 / 1024).toFixed(2)}MB)`);
    });

    console.log('\n🚀 开始图片优化演示...\n');

    // 对每个图片进行优化演示
    for (let i = 0; i < Math.min(testFiles.length, 3); i++) {
        const testFile = testFiles[i];
        console.log(`📸 处理图片 ${i + 1}: ${testFile}`);

        try {
            const originalStats = fs.statSync(testFile);
            const originalSize = originalStats.size;
            const originalSizeMB = (originalSize / 1024 / 1024).toFixed(2);

            // 不同质量等级的优化
            const qualityLevels = ['high', 'medium', 'low'];

            for (const quality of qualityLevels) {
                console.log(`   🎯 质量等级: ${quality}`);

                const startTime = Date.now();
                const result = await optimizer.optimizeImage(testFile, {
                    ...optimizer.getQualityConfig(quality),
                    enableLossyCompression: true,
                    convertToJPEG: true,
                    stripMetadata: true
                });
                const endTime = Date.now();

                const compressionRate = ((1 - result.optimizedInfo.size / originalSize) * 100).toFixed(1);
                const processingTime = endTime - startTime;

                console.log(`      原始: ${originalSizeMB}MB (${originalSize.toLocaleString()} bytes)`);
                console.log(`      优化后: ${result.optimizedInfo.sizeMB}MB (${result.optimizedInfo.size.toLocaleString()} bytes)`);
                console.log(`      压缩率: ${compressionRate}%`);
                console.log(`      处理时间: ${processingTime}ms`);
                console.log(`      格式: ${result.originalInfo.format} → ${result.optimizedInfo.format}`);
                console.log(`      尺寸: ${result.originalInfo.width}×${result.originalInfo.height} → ${result.optimizedInfo.width}×${result.optimizedInfo.height}`);

                // 保存优化后的图片
                const outputFileName = `optimized-${quality}-${testFile.replace(/\.(jpg|jpeg|png)$/i, '.jpg')}`;
                const optimizedBuffer = Buffer.from(result.data.split(',')[1], 'base64');
                fs.writeFileSync(outputFileName, optimizedBuffer);
                console.log(`      输出文件: ${outputFileName}`);
                console.log('');
            }

        } catch (error) {
            console.error(`   ❌ 处理失败:`, error.message);
        }

        console.log('---');
    }

    // 性能测试
    console.log('\n⚡ 性能测试 - 批量优化');

    const testImage = testFiles[0];
    const base64Data = fs.readFileSync(testImage).toString('base64');
    const batchSize = 10;

    console.log(`   批量处理 ${batchSize} 次相同图片...`);

    const startTime = Date.now();
    const promises = [];

    for (let i = 0; i < batchSize; i++) {
        promises.push(optimizer.optimizeImage(base64Data, {
            ...optimizer.getQualityConfig('medium'),
            enableLossyCompression: true,
            convertToJPEG: true
        }));
    }

    const results = await Promise.all(promises);
    const endTime = Date.now();

    const totalTime = endTime - startTime;
    const avgTime = totalTime / batchSize;
    const throughput = (batchSize / (totalTime / 1000)).toFixed(2);

    console.log(`   总时间: ${totalTime}ms`);
    console.log(`   平均时间: ${avgTime.toFixed(2)}ms`);
    console.log(`   吞吐量: ${throughput} 图片/秒`);

    // 验证结果一致性
    const firstSize = results[0].optimizedInfo.size;
    const allSameSize = results.every(result => result.optimizedInfo.size === firstSize);
    console.log(`   结果一致性: ${allSameSize ? '✅ 通过' : '❌ 失败'}`);

    console.log('\n🎉 图片优化系统演示完成！');

    // 总结
    console.log('\n📊 功能总结:');
    console.log('   ✅ 支持多种图片格式 (JPEG, PNG, GIF, WebP)');
    console.log('   ✅ 智能质量等级选择 (high, medium, low, ultra)');
    console.log('   ✅ 自动格式转换 (PNG → JPEG)');
    console.log('   ✅ 智能分辨率调整');
    console.log('   ✅ 元数据清理');
    console.log('   ✅ Sharp库集成 (高质量转换)');
    console.log('   ✅ 批量处理支持');
    console.log('   ✅ 错误处理和降级机制');
    console.log('   ✅ 性能监控和优化');

    console.log('\n💡 使用建议:');
    console.log('   • 对于高质量分析任务，使用 high 质量等级');
    console.log('   • 对于快速预览，使用 medium 质量等级');
    console.log('   • 对于网络传输，使用 low 质量等级');
    console.log('   • 对于超大文件，使用 ultra 质量等级');
    console.log('   • 系统会自动选择最佳配置，无需手动干预');
}

// 运行演示
demonstrateImageOptimization().catch(console.error);